# encoding: utf-8
"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lane.chang on '11/05/2025'
    comment: 业务逻辑层一些公共依赖
"""
import re
import json
from project.output.conversations import CONVERSATIONS_FOLDER


def assemble_prompt(md_file, **kwargs):
    """
    :param md_file:
    :param kwargs:
    :return:
    """
    prompt = open(md_file).read()
    for key, value in kwargs.items():
        prompt = prompt.replace(f'{{{key}}}', value)

    return prompt


def extract_json(md_text: str):
    """
    :return:
    """
    match = re.search(r'```json\s*(\{.*?\})\s*```', md_text, flags=re.S)
    if not match:
        return ''

    try:
        result = json.loads(match.group(1))
    except Exception as ex:
        raise ValueError(f'JSON parsing failed. err: {ex}')

    return result


def write_conversation(conversation_code, message: str, reply: str, duration: int = 0):
    """ 记录模型会话日志
    :param conversation_code:
    :param message: 用户的话术
    :param reply: 模型的返回
    :param duration: 推理时长 单位: 秒
    :return:
    """
    with open(f'{CONVERSATIONS_FOLDER}/{conversation_code}.log', 'a+', encoding='utf-8') as f:
        f.write(json.dumps({'message': message, 'reply': reply, 'duration': duration}) + '\n')


def get_conversations(conversation_code):
    """ 取得模型会话日志
    :param conversation_code:
    :return:
    """
    data = []
    with open(f'{CONVERSATIONS_FOLDER}/{conversation_code}.log', 'r', encoding='utf-8') as f:
        for line in f:
            data.append(json.loads(line))

    return data


if __name__ == "__main__":

    text = '123'
    print(json.loads(text))
